if (typeof (tio) == "undefined") {
    tio = {};
}
tio.ws = {};

tio.ws = function ($, layim) {

    // 心跳超时时间，单位：毫秒
    this.heartbeatTimeout = 5000;
    // 心跳发送间隔 = 心跳超时时间 / 2
    this.heartbeatSendInterval = this.heartbeatTimeout / 2;

    var self = this;

    this.connect = function () {
        var url = "ws://127.0.0.1:8989?userId=" + self.userId + "&username=" + self.username;
        // var url = "ws://123.56.46.23:8989?userId=" + self.userId + "&username=" + self.username;
        var websocket = new WebSocket(url);
        self.websocket = websocket;
        websocket.onopen = function () {
            console.log("tio ws 启动");

            // 生成最后交互时间
            self.lastInteractionTime(new Date().getTime());

            // 建立心跳
            self.ping();
        }
        websocket.onclose = function () {
            console.log("tio ws 关闭");

            // 尝试重新连接
            self.reconnect();
        }
        websocket.onmessage = function (res) {
            console.log("接收到消息！！");
            console.log(res.data);
            var imMessage = eval('(' + res.data + ')');
            console.log("------------消息转成JSON之后-----------");
            console.log(imMessage);

            if (imMessage.type === 'chatMessage') {
                layim.getMessage(imMessage.from);
            }

            // 生成最后交互时间
            self.lastInteractionTime(new Date().getTime());
        }
    }

    this.getUserAndGroupAndWindows = function () {
        // 获取个人信息
        $.ajax({
            url: '/im-chat/getUserAndGroup',
            async: false,
            success: function (res) {
                self.imGroup = res.data.imGroup;
                self.imUser = res.data.imUser;
                self.userId = self.imUser.id;
                self.username = self.imUser.username;
            }
        });

        console.log(self.imGroup);
        console.log(self.imUser);

        // 入缓存
        var cache = layui.layim.cache();
        cache.mine = self.imUser

        // 打开窗口
        layim.chat(self.imGroup);
        // 收缩聊天面板
        layim.setChatMin();
    }

    // 发送消息
    this.sendChatMessage = function (res) {
        console.log(res);
        self.websocket.send(JSON.stringify({
            type: 'chatMessage',
            data: res
        }));
    }

    // 获取群历史消息
    this.getGroupHistoryMessage = function () {
        localStorage.clear();
        $.ajax({
            url: '/im-chat/getGroupHistoryMessage',
            success: function (res) {
                console.log(res);
                var data = res.data;
                if (data.length < 1) {
                    return;
                }

                for (var i in data) {
                    layim.getMessage(data[i]);
                }

            }
        })
    }
    
    // -------------------------重试机制-------------------------
    // 生成最后交互时间
    this.lastInteractionTime = function () {
        if (arguments.length == 1) {
            this.lastInteractionTimeValue = arguments[0];
        }
        return this.lastInteractionTimeValue;
    }

    this.ping = function () {
        console.log("im.js---------------->准备心跳中");

        // 建立一个定时器，定时心跳，每2.5秒心跳一次
        self.pingIntervalId = setInterval(function () {
            // 有多长时间没有发消息了 = 当前时间 - 最后交互时间
            var iv = new Date().getTime() - self.lastInteractionTime();

            // 2.5 + 3 >= 5
            // 如果心跳发送间隔 + 有多长时间没发消息了 >= 心跳超时时间
            if ((self.heartbeatSendInterval + iv) >= self.heartbeatTimeout) {
                // 发送进行心跳
                self.websocket.send(JSON.stringify({
                    type: 'pingMessage',
                    data: 'ping'
                }))
                console.log("im.js---------------->正在心跳中")
            }
        }, self.heartbeatSendInterval)
    }

    this.reconnect = function () {
        // 先删除心跳定时器
        clearInterval(self.pingIntervalId);

        // 然后尝试建立新的连接，也就是重新连接
        self.connect();
    }

}